package com.ztf0337.mycurriculumdesign.database;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

import com.ztf0337.mycurriculumdesign.dao.OrderDao;
import com.ztf0337.mycurriculumdesign.dao.ParkLotDao;
import com.ztf0337.mycurriculumdesign.dao.ParkingSpaceDao;
import com.ztf0337.mycurriculumdesign.dao.RentDao;
import com.ztf0337.mycurriculumdesign.dao.UserDao;
import com.ztf0337.mycurriculumdesign.entity.Order;
import com.ztf0337.mycurriculumdesign.entity.ParkLot;
import com.ztf0337.mycurriculumdesign.entity.ParkingSpace;
import com.ztf0337.mycurriculumdesign.entity.RentedParkingSpace;
import com.ztf0337.mycurriculumdesign.entity.User;


@Database(entities = {
        User.class,
        ParkingSpace.class,
        Order.class,
        ParkLot.class,
        RentedParkingSpace.class},
        version = 1)
public abstract class AppDatabase extends RoomDatabase {
    private static volatile AppDatabase INSTANCE;

    public abstract UserDao userDao();
    public abstract ParkLotDao parkLotDao();
    public abstract OrderDao orderDao();
    public abstract ParkingSpaceDao parkingSpaceDao();
    public abstract RentDao rentDao();

    public static AppDatabase getInstance(Context context) {
        if (INSTANCE == null) {                          // 1. 第一次调用，INSTANCE 为空
            synchronized (AppDatabase.class) {          // 2. 加锁，避免多线程同时创建实例
                if (INSTANCE == null) {                  // 3. 双重检查，确保线程安全
                    INSTANCE = Room.databaseBuilder(    // 4. 通过 Room 创建数据库实例
                                    context.getApplicationContext(),
                                    AppDatabase.class,
                                    "app_database"                   // 5. 数据库名
                            )
                            .allowMainThreadQueries()            // 6. 允许主线程查询（开发阶段方便调试，正式项目不建议）
                            .fallbackToDestructiveMigration() // 💥 破坏时重建
                            .build();                            // 7. 构建数据库实例
                }
            }
        }
        return INSTANCE;                                // 8. 返回单例实例
    }

}
